package workers

import (
	"black_mamba/global"
	"fmt"
	"gitee.com/wengo/go-amazon"
	"gitee.com/wengo/go-mamba"
	"github.com/PuerkitoBio/goquery"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"math/rand"
	"regexp"
	"strings"
)

type CrawlerWorker struct {
	Worker
}

func NewCrawlerWorker() *CrawlerWorker {
	return &CrawlerWorker{
		Worker{
			Topic: "crawler",
		},
	}
}

func (d *CrawlerWorker) Execute(data map[string]interface{}) (ret interface{}) {
	/*
		   流程
		    1.访问首页
			2.新建收货地址，新建信用卡
			3.打开Listing
			4.加入购物车
			5.结账
			6.选择地址
			7.选择信用卡
			8.建立订单
	*/

	//defer func() {
	//	//可以打印错误信息
	//	//recover()
	//	//fmt.Println(recover())
	//
	//	//没有错就不要打印
	//	if err := recover(); err != nil { //产生了panic异常
	//		stackStr := string(debug.Stack())
	//		utils.WriteFile("error.log", fmt.Sprintf("%s\n%s\n", err, stackStr))
	//	}
	//}()

	var resp *mamba.Response
	var document *goquery.Document
	var err error
	//
	//website := gjson.Get(data["tasks"].(string), "list.0.website.value").String()
	//code := gjson.Get(data["tasks"].(string), "list.0.code.value").String()
	website := "www.amazon.com"
	code := "us"

	//user, err := global.BM_API.GetCrawlerCookies()

	//Win7:
	//Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1
	//Mozilla/5.0 (Windows NT 10; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1
	//Mozilla/5.0 (Windows NT 11; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1
	system := []string{"6.1", "10", "11"}
	browse := []string{"100", "101", "102", "103", "104", "105", "106"}
	bit := []string{"Win64", "Win64, x64", "WOW64", "Win32"}

	ua := fmt.Sprintf("Mozilla/5.0 (Windows NT %s; %s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s.0.5060.66 Safari/537.36", system[rand.Intn(len(system))], bit[rand.Intn(len(bit))], browse[rand.Intn(len(browse))])
	fmt.Println(ua)
	amz := amazon.NewAmazon(amazon.Settings{
		//JA3:       "771,4JUdGzvrMFDWrUUwY3toJATSeNwjn54LkCnKBPRzDuhzi5vSepHfUckJNxRL2gjkNrSqtCoRUrEDAgRwsQvVCjZbRyFTLRNyDmT1a1boZV",
		//UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
		JA3:       "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-17513,29-23-24,0",
		UserAgent: ua,
		//UserAgent: "Mozilla/5.0 (Windows NT 7; Win64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5060.66 Safari/537.36",
		BaseUri: fmt.Sprintf("https://%s", website),
		//BaseUri:     "https://www.amazon.com",
		Header: map[string]interface{}{"Accept-Language": "en-US;q=0.8,en;q=0.7"},
		//Cookies: nil,
		Cookies:     nil,
		Debug:       true,
		DebugLength: 100000,
		//Proxy:       proxy,
		//Proxy: `http://127.0.0.1:8080`,
		//Proxy: `http://192.168.2.5:8080`,
		//Proxy:       `http://127.0.0.1:24000`,
		//Proxy: `http://FE6FC783:E0C53AF2F7CD@119.114.23.221:45350`,
		//Proxy: `http://lum-customer-c_17e58ad2-zone-residential:Jjyylu102697@zproxy.lum-superproxy.io:22225`,
		//Proxy: fmt.Sprintf("http://%s:%s@tunnel5.qg.net:14295", global.BM_CONFIG.Section("proxy").Key("username").Value(), global.BM_CONFIG.Section("proxy").Key("password").Value()),
		Proxy: fmt.Sprintf("http://%s:%s@http-dynamic.xiaoxiangdaili.com:10030", global.BM_CONFIG.Section("proxy").Key("username").Value(), global.BM_CONFIG.Section("proxy").Key("password").Value()),
	})

	var responsePath, responseUrl string

	resp, document, err = amz.Navigate(fmt.Sprintf("/dp/%s", data["asin"]))
	if err != nil {
		d.sendLog(map[string]string{"status": "error", "content": fmt.Sprintf("%s -> %s", err.Error(), ua)})
	} else {
		d.sendLog(map[string]string{"status": "success", "content": fmt.Sprintf("%s, status = %d", data["asin"], resp.StatusCode())})
	}

	return
	continueExecute := true
	for continueExecute {
		switch {
		case resp == nil: // 首页
			d.sendLog(map[string]string{"status": "info", "content": "打开首页"})
			switch code {
			case "de", "uk", "fr":
				resp, document, err = amz.Navigate("/cookieprefs")
			default:
				resp, document, err = amz.Navigate("/")
			}

			if err != nil {
				d.sendLog(map[string]string{"status": "info", "content": err.Error()})
				return
			}
		case responsePath == "/cookieprefs":
			resp, document, err = amz.AcceptAllCookies(document)
			if err != nil {
				resp = nil
				continue
			}
		case responsePath == "/":
			var postalCode string
			zipCode, _ := global.BM_API.GetZipCode(code, global.BM_CONFIG.Section("basic").Key("serialNumberCiphertext").Value())
			postalCode = zipCode.ZipCode

			resp, err = amz.ChangeAddress(document, postalCode)
			//resp, err = amz.ChangeAddress(document, amazon.Choice(zipCode))
			if err != nil {
				d.sendLog(map[string]string{"status": "error", "content": err.Error()})
				return
			} else {
				if gjson.Get(resp.String(), "address.zipCode").String() == "" {
					d.sendLog(map[string]string{"status": "error", "content": fmt.Sprintf("%s -> 邮编无效, 换邮编", postalCode)})
					resp, document, err = amz.Navigate("/")
					continue
				} else {
					d.sendLog(map[string]string{"status": "info", "content": fmt.Sprintf("已把地址修改为: %s %s", gjson.Get(resp.String(), "address.city").String(), gjson.Get(resp.String(), "address.zipCode").String())})
				}
			}

		case responsePath == `/gp/delivery/ajax/address-change.html`: // 在任务页面做任务或者尝试登陆页面做任务
			listing := data["listing"].(string)
			asin := strings.Split(listing, "/")[2]
			d.sendLog(map[string]string{"status": "info", "content": fmt.Sprintf("查看 %s listing", asin)})
			resp, document, err = amz.Navigate(listing)
			if err != nil {
				d.sendLog(map[string]string{"status": "error", "content": err.Error()})
				return
			}

			if document.Find("#outOfStock").Length() > 0 && document.Find(".reviews-content").Length() == 0 && document.Find("#reviews-medley-global-expand-head").Length() == 0 {
				if document.Find("i[data-hook='average-star-rating'] span").Length() > 0 {
					d.sendLog(map[string]string{"status": "success", "content": fmt.Sprintf("%s 符合搜刮条件, 发送回服务器", asin)})
					matcher := regexp.MustCompile(`\d+\.\d+`)
					result := matcher.FindStringSubmatch(document.Find("i[data-hook='average-star-rating'] span").Text())
					rating := result[0]
					global.BM_API.AsinFeedBack(listing, rating, "", strings.TrimSpace(document.Find("#productTitle").Text()))
				}
			} else {
				d.sendLog(map[string]string{"status": "info", "content": fmt.Sprintf("%s 不符合搜刮条件", asin)})
			}

			continueExecute = false
		default:
			d.sendLog(map[string]string{"status": "error", "content": fmt.Sprintf("未知内容, 退出, 当前页面: %s", responseUrl)})

			ioutil.WriteFile("unknown.html", resp.Body(), 0644)
			continueExecute = false
		}

		if resp != nil {
			responsePath = resp.RawResponse.Request.URL.Path
			responseUrl = resp.RawResponse.Request.URL.String()
		}
	}

	var statistic map[string]string
	//total := utils.ArrayCountValues(accountStatistic[user.Emailaddress]["success"].([]interface{}))
	//global.BM_EVENTBUS.Publish("deals:feedback", total)
	//
	//statisticFormat := fmt.Sprintf("\n 邮箱    : %s\t\n 邮编    : %s\n 收货地址: %s\n 信用卡号: %s\n asins:   %s\n 订单总数: %d\n 订单列表: %s\n===========================================",
	//	user.Emailaddress,
	//	accountStatistic[user.Emailaddress]["zipCode"],
	//	accountStatistic[user.Emailaddress]["address"],
	//	accountStatistic[user.Emailaddress]["cc"],
	//	strings.Join(utils.RemoveDuplicateStr(accountStatistic[user.Emailaddress]["asins"].([]string)), "\t"),
	//	len(accountStatistic[user.Emailaddress]["orders"].([]string)),
	//	strings.Join(accountStatistic[user.Emailaddress]["orders"].([]string), "\t"),
	//)
	//
	//statistic = map[string]string{"status": "info", "content": statisticFormat}

	return statistic
}
